<template>
  <div class="editor" v-loading="isLoading">
    <div class="header">
      <img src="../../assets/editor/logo.png" class="logo" />
      <div class="nav">
        <span class="nav-item active">网站中心</span>
        <span class="nav-item">模版管理</span>
      </div>
      <div class="user">
        <div class="avatar">
          <img :src="userStore.avatar" class="user-avatar" />
        </div>
        <el-dropdown @command="handleCommand" class="right-menu-item hover-effect" trigger="click">
          <div class="username">{{ userStore.name }}</div>
          <template #dropdown>
            <el-dropdown-menu>
              <router-link to="/user/profile" v-if="!dynamic">
                <el-dropdown-item>{{ $t('navbar.personalCenter') }}</el-dropdown-item>
              </router-link>
              <el-dropdown-item command="setLayout" v-if="settingsStore.showSettings">
                <span>{{ $t('navbar.layoutSetting') }}</span>
              </el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <span>{{ $t('navbar.logout') }}</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <div class="body">
      <div class="sidebar">
        <div class="tips">
          <div class="label">开始装修：</div>
          <div class="tips-content">点击组件至中间画布的对应位置</div>
        </div>
        <div class="sidebar-tabs">
          <span class="sidebar-tab-item active">组件管理</span>
          <span class="sidebar-tab-item">栏目管理</span>
        </div>
        <div class="component-menu">
          <div
            class="component-group"
            @click="onSideBarMenuClick(item)"
            :class="{ active: item.id === activeMenuItem }"
            v-for="(item, index) in sideBarMenuList"
            :key="index"
          >
            {{ item.name }}
          </div>
        </div>
      </div>
      <div class="editor-content">
        <div class="page-content">
          <div class="component-rect" @click="onComponentRectClick(item, index)" v-for="(item, index) in editComponentList" :key="index">
            <component :is="item.component" :data="item.props.data" />
            <div class="button-area" v-if="item.active">
              <img src="../../assets/editor/dropup-arrow.png" class="dropup button-icon" @click.stop="doSortUp(item, index)" />
              <img src="../../assets/editor/dropdown-arrow.png" class="dropdown button-icon" @click.stop="doSortDown(item,index)" />
              <img src="../../assets/editor/remove.png" class="remove button-icon" @click.stop="doRemove(index)" />
            </div>
          </div>
        </div>
      </div>
      <div class="props-form" v-if="showRightPropsForm">
        <!--
          实际组件配置项应该与组件库配套 即整合到一起
          通常情况下只有组件开发者才会了解组件的配置项有哪些 故顺便完成配置项的配套
        -->
        <!-- <button @click="changeActiveEditComponentProps">点击</button> -->
        <component
          :is="editComponentList[activeEditComponentIndex].propsFormComponentName"
          :data="editComponentList[activeEditComponentIndex].props.data"
          @configChanged="changeActiveEditComponentProps"
        />
      </div>
    </div>
    <div class="bottom">
      <el-button type="primary" @click="doSave">保存</el-button>
      <el-button @click="preview">预览</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
interface SideBarMenuItem {
  id: string,
  name: string,
  component: any,
  propsFormComponentName: string,
  props: any,
  active?: boolean,
  componentPath?: string,
  componentVersion?: string,
  isActive?: boolean,
  icon?: string,
}

import { ref } from 'vue'
import useUserStore from '@/store/modules/user';
import useSettingsStore from '@/store/modules/settings';
import { listComponent } from '@/api/logic/component';
import { useRouter, useRoute } from 'vue-router';
import { saveEditorConfig, getEditorConfig } from '@/api/editor';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const router = useRouter();
const route = useRoute();

const isLoading = ref(true);
const userStore = useUserStore();
const settingsStore = useSettingsStore();
const showRightPropsForm = ref(false);
const activeMenuItem = ref('');
const activeEditComponentIndex = ref<number>(0);
// 是否切换了租户
const dynamic = ref(false);

const emits = defineEmits(['setLayout'])
const setLayout = () => {
    emits('setLayout');
}

const logout = async () => {
    await ElMessageBox.confirm('确定注销并退出系统吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await userStore.logout()
    location.href = import.meta.env.VITE_APP_CONTEXT_PATH + 'index';
}

// 定义Command方法对象 通过key直接调用方法
const commandMap: {[key: string]: any} = {
    setLayout,
    logout
};

const handleCommand = (command: string) => {
    // 判断是否存在该方法
    if (commandMap[command]) {
        commandMap[command]();
    }
}

/**
 * 左侧菜单列表中的组件
 * 在页面加载后应该直接从接口中获取
 */
const sideBarMenuList = ref<SideBarMenuItem[]>([
  // {
  //   id: '1',
  //   name: '顶部组件',
  //   // component后面应该对应的是组件的名称
  //   // 需要提前注册组件库
  //   component: TopComponent,
  //   propsFormComponentName: '',
  //   props: {
  //     data: {
  //       type: 'D'
  //     }
  //   }
  // } as SideBarMenuItem,
  // {
  //   id: '2',
  //   name: '底部组件',
  //   component: BottomComponent,
  //   props: {
  //     data: {
  //       type: 'D'
  //     }
  //   }
  // } as SideBarMenuItem,
  // {
  //   id: '3',
  //   name: '广告位组件',
  //   component: AdComponent,
  //   props: {
  //     data: {
  //       type: 'D'
  //     }
  //   }
  // } as SideBarMenuItem,
  // {
  //   id: '4',
  //   name: '产品组件',
  //   component: ProductComponent,
  //   props: {
  //     data: {
  //       type: 'D'
  //     }
  //   }
  // } as SideBarMenuItem
])

/** 查询组件管理列表 */
const getList = async () => {
  const res = await listComponent({
    pageNum: 1,
    pageSize: 100,
  });
  sideBarMenuList.value = res.rows.map(e=>{
    return {
      id: e.componentId,
      name: e.componentName,
      // component后面应该对应的是组件的名称
      // 需要提前注册组件库
      component: e.type,
      propsFormComponentName: e.confLable,
      props: {
        data: e.componentConfiguration == null ? {} : JSON.parse(e.componentConfiguration.replaceAll('\n', ''))
      },
      componentPath: e.componentPath,
      componentVersion: e.componentVersion,
      isActive: true,
      icon: e.icon,
    } as SideBarMenuItem;
  });
}

/**
 * 获取网站配置信息
 */
const getWebsideEditorConfig = async () => {
  isLoading.value = true;
  const websideId = route.query.websideId;

  if (websideId == null || websideId == '') {
    proxy?.$modal.alertError('未获取到网站ID');
    isLoading.value = false;
    return;
  }

  try {
    const res = await getEditorConfig(websideId);
    editComponentList.value = res.data.components.map((e:any) => {
      return {
        id: e.componentId,
        name: e.componentName,
        // component后面应该对应的是组件的名称
        // 需要提前注册组件库
        component: e.type,
        propsFormComponentName: e.confLable,
        props: {
          data:e.componentConfiguration == null ? {} : JSON.parse(e.componentConfiguration.replaceAll('\n', ''))
        },
        componentPath: e.componentPath,
        componentVersion: e.componentVersion,
        isActive: true,
        icon: e.icon,
      } as SideBarMenuItem;
    });
    console.log(editComponentList.value);
  } finally {
    isLoading.value = false;
  }
}

// 编辑器窗口中的组件列表
const editComponentList = ref<Array<SideBarMenuItem>>([]);

// 左侧组件列表点击事件
const onSideBarMenuClick = (item: SideBarMenuItem) => {
  // 左侧高亮
  activeMenuItem.value = item.id;
  editComponentList.value.forEach((e:any)=>{
    e.active = false;
  });
  editComponentList.value.push({
    ...item,
    active: true
  });
  activeEditComponentIndex.value = editComponentList.value.length - 1;
  showRightPropsForm.value = true;
}

// 编辑区域组件点击
const onComponentRectClick = (item: SideBarMenuItem, index: number) => {
  activeEditComponentIndex.value = index;
  editComponentList.value.forEach((e:any)=>{
    e.active = false;
  });
  item.active = true;
  showRightPropsForm.value = true;
}

const changeActiveEditComponentProps = (e: any) => {
  console.log(e);
  editComponentList.value[activeEditComponentIndex.value].props = {
    data: e.config
  }
}

const doSortUp = (item: any, index:number) => {
  // 位置0 无法向上
  if (index == 0) {
    return
  }

  const editComponentListVal = editComponentList.value;
  const positionIndex = index - 1;
  const temp = editComponentListVal[positionIndex];
  editComponentListVal[positionIndex] = editComponentListVal[index];
  editComponentListVal[index] = temp;

  activeEditComponentIndex.value = positionIndex;
}

const doSortDown = (item: SideBarMenuItem, index:number) => {
  // 位置底部 无法向下排序
  if (index == editComponentList.value.length - 1) {
    return
  }

  const editComponentListVal = editComponentList.value;
  const positionIndex = index + 1;
  const temp = editComponentListVal[positionIndex];
  editComponentListVal[positionIndex] = editComponentListVal[index];
  editComponentListVal[index] = temp;

  activeEditComponentIndex.value = positionIndex;
}

// 移除组件
const doRemove = (index:number) => {
  editComponentList.value.splice(index, 1);
  showRightPropsForm.value = false;
}

const doSave = async (callback: any) => {
  if (editComponentList.value.length == 0) {
    proxy?.$modal.msgWarning("未获取到网站配置");
    return;
  }

  isLoading.value = true;
  const websideId = route.query.websideId;
  const componentConfigList = editComponentList.value.map((e: SideBarMenuItem) => {
    return {
      componentId: e.id,
      componentName: e.name,
      componentPath: e.componentPath ?? '',
      componentVersion: e.componentVersion,
      componentConfiguration: JSON.stringify(e.props.data),
      isActive: 0,
      icon: e.icon,
      confLable: e.propsFormComponentName,
      compontLable: e.name,
      type: e.component
    };
  });
  try {
    console.log(websideId);
    console.log(componentConfigList);
    const res = await saveEditorConfig({
      websiteId: websideId,
      components: componentConfigList,
    });
    console.log(res);
    if (res.code == 200) {
      // proxy?.$modal.alertSuccess('网站配置保存成功');
      proxy?.$modal.msgSuccess('网站配置保存成功');
      callback.call();
    }
  } finally {
    isLoading.value = false;
  }
}

const preview = () => {
  proxy?.$modal.confirm('是否保存并预览？').then(()=>{
    doSave(()=>{
      router.push({
        path: '/editor/preview',
        query: route.query
      })
    });
  });

}

const cancel = () => {
  router.back();
}

onMounted(() => {
  getList();
  getWebsideEditorConfig();
});
</script>

<style lang="scss" scoped>
.editor {
  width: 100vw;
  height: 100vh;
  background-color: #EFEFEF;
  overflow: hidden;
  min-width: 1500px;

  .header {
    height: 64px;
    background: #FAFAFA;
    display: flex;
    flex-direction: row;
    align-items: center;
    border-bottom: 1px solid #EFEFEF;

    .logo {
      width: 111px;
      height: 28px;
      margin-left: 20px;
    }

    .nav {
      display: flex;
      flex-direction: row;
      flex: 1;
      justify-content: center;

      .nav-item {
        margin: 0 36px;
        color: #A8B0BC;
        font-size: 16px;
        font-weight: 500;

        &.active {
          color: #3D3D3D;
        }
      }
    }

    .user {
      margin-right: 24px;
      display: flex;
      flex-direction: row;
      align-items: center;

      .avatar {
        width: 32px;
        height: 32px;
        border-radius: 32px;
        margin-right: 12px;
        overflow: hidden;

        img {
          width: 100%;
        }
      }

      .username {
        font-size: 12px;
        color: #3D3D3D;
        font-weight: 500;
        padding: 0 12px;
        position: relative;

        &::after {
          position: absolute;
          content: '';
          width: 16px;
          height: 16px;
          right: -12px;
          background: url(../../assets/editor/arrow-dropdown.png);
          background-repeat: no-repeat;
          background-size: 16px 16px;
        }
      }
    }
  }

  .body {
    height: calc(100vh - 154px);
    background-color: #EFEFEF;
    width: 100%;
    display: flex;
    flex-direction: row;

    .sidebar {
      width: 244px;
      height: 100%;
      background: #FAFAFA;
      overflow-y: auto;
      display: flex;
      flex-direction: column;

      .tips {
        padding: 20px;
        border-bottom: 1px solid #EFEFEF;

        .label {
          font-size: 14px;
          color: #3D3D3D;
          font-weight: 500;
        }

        .tips-content {
          margin-top: 6px;
          font-size: 12px;
          color: #A8B0BC;
          font-weight: 500;
        }
      }

      .sidebar-tabs {
        border-bottom: 1px solid #EFEFEF;

        .sidebar-tab-item {
          margin: 20px;
          font-size: 14px;
          font-weight: 500;
          display: inline-block;
          color: #A8B0BC;
          cursor: pointer;

          &.active {
            color: #3D3D3D;
          }
        }
      }

      .component-menu {
        flex: 1;
        overflow-y: auto;
        padding-top: 10px;

        .component-group {
          padding: 10px 20px;
          cursor: pointer;
          color: #3D3D3D;

          &.active {
            background-color: #C4DBFF !important;
            color: #096AFF;
          }

          &:hover {
            background-color: #EBEEF3;
          }
        }
      }
    }

    .editor-content {
      width: calc(100vw - 244px - 280px);
      height: 100%;
      flex: 1;
      overflow-y: auto;
      padding: 25px 98px;

      .page-content {
        width: 100%;
        min-height: 500px;
        background-color: #FFFFFF;

        .component-rect {
          position: relative;

          .button-area {
            position: absolute;
            background-color: #FFF;
            right: -50px;
            top: 0;
            border-radius: 2px;

            .button-icon {
              width: 36px;
              height: 36px;
              cursor: pointer;
              display: block;
              border-bottom: 1px solid #EFEFEF;
            }
          }
        }
      }
    }

    .props-form {
      width: 280px;
      height: 100%;
      overflow-y: auto;
      background-color: #FAFAFA;
    }
  }

  .bottom {
    height: 90px;
    background: #FFFFFF;
    text-align: center;
    padding-top: 17px;
  }
}
</style>
